package com.gin.kotlin.no_gay_alliance.fragment.main.setting

import android.view.View
import com.gin.kotlin.no_gay_alliance.adapter.AppReleaseAdapter
import com.gin.kotlin.no_gay_alliance.argument.AppReleaseArgument
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingFragment
import com.gin.kotlin.no_gay_alliance.callback.SCallback
import com.gin.kotlin.no_gay_alliance.databinding.FragmentMainSettingAppReleaseBinding
import com.gin.kotlin.no_gay_alliance.model.AppReleaseModel
import com.gin.kotlin.no_gay_alliance.provider.thirdparty.AppReleaseProvider
import okhttp3.Call
import java.io.IOException

class AppReleaseFragment : AbstractBindingFragment<FragmentMainSettingAppReleaseBinding>(), SCallback<List<AppReleaseModel>> {
    private var params: AppReleaseArgument? = null
    private lateinit var adapter: AppReleaseAdapter

    override fun onCreateView() {
        val b = this.b ?: return
        this.adapter = AppReleaseAdapter(requireContext(), handler!!)
        params = AppReleaseArgument()
        b.swipeRefreshLayout.setOnRefreshListener { request(true) }
        b.recyclerView.adapter = adapter
        request()
    }


    private fun request(ignoreCache: Boolean = false) {
        val b = this.b ?: return
        b.tvWarning.visibility = View.GONE
        b.swipeRefreshLayout.isRefreshing = true
        AppReleaseProvider.getInstance().enqueue(this.params,ignoreCache=ignoreCache, callback = this)
    }

    override fun onSuccess(data: List<AppReleaseModel>) {
        val b = this.b ?: return
        b.swipeRefreshLayout.isRefreshing = false
        adapter.replaceData(data)
    }

    override fun onFailure(call: Call, e: IOException) {
        val b = this.b ?: return
        b.tvWarning.text = e.localizedMessage
        b.tvWarning.visibility = View.VISIBLE
        b.swipeRefreshLayout.isRefreshing = false
    }
}